import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import '../themes/expense_theme.dart';

/// 增强的年份选择器
class EnhancedYearPicker extends StatefulWidget {
  final int initialYear;
  final int? startYear;
  final int? endYear;
  final Function(int) onYearSelected;
  final String? title;

  const EnhancedYearPicker({
    super.key,
    required this.initialYear,
    required this.onYearSelected,
    this.startYear,
    this.endYear,
    this.title,
  });

  @override
  State<EnhancedYearPicker> createState() => _EnhancedYearPickerState();
}

class _EnhancedYearPickerState extends State<EnhancedYearPicker>
    with SingleTickerProviderStateMixin {
  late int _selectedYear;
  late ScrollController _scrollController;
  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;
  late List<int> _years;

  @override
  void initState() {
    super.initState();
    _selectedYear = widget.initialYear;
    
    final currentYear = DateTime.now().year;
    final startYear = widget.startYear ?? (currentYear - 10);
    final endYear = widget.endYear ?? (currentYear + 5);
    
    _years = List.generate(
      endYear - startYear + 1,
      (index) => startYear + index,
    ).reversed.toList(); // 倒序排列，最新年份在前
    
    _scrollController = ScrollController();
    
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    
    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));
    
    _slideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.3),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeOutCubic,
    ));
    
    _animationController.forward();
    
    // 滚动到选中的年份
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _scrollToSelectedYear();
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: Colors.transparent,
      child: FadeTransition(
        opacity: _fadeAnimation,
        child: SlideTransition(
          position: _slideAnimation,
          child: Container(
            constraints: BoxConstraints(
              maxWidth: 300.w,
              maxHeight: 500.h,
            ),
            decoration: BoxDecoration(
              color: ExpenseTheme.cardBackground,
              borderRadius: BorderRadius.circular(20.r),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withValues(alpha: 0.1),
                  blurRadius: 20,
                  offset: const Offset(0, 10),
                ),
              ],
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                _buildHeader(),
                _buildYearList(),
                _buildActions(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建头部
  Widget _buildHeader() {
    return Container(
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        gradient: ExpenseTheme.primaryGradient,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20.r),
          topRight: Radius.circular(20.r),
        ),
      ),
      child: Row(
        children: [
          Icon(
            Icons.youtube_searched_for,
            color: Colors.white,
            size: 24.sp,
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: Text(
              widget.title ?? '选择年份',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
                color: Colors.white,
              ),
            ),
          ),
          IconButton(
            onPressed: () => Navigator.of(context).pop(),
            icon: Icon(
              Icons.close,
              color: Colors.white,
              size: 20.sp,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建年份列表
  Widget _buildYearList() {
    return Expanded(
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
        child: ListView.builder(
          controller: _scrollController,
          itemCount: _years.length,
          itemBuilder: (context, index) {
            final year = _years[index];
            final isSelected = year == _selectedYear;
            final isCurrentYear = year == DateTime.now().year;
            
            return Container(
              margin: EdgeInsets.symmetric(vertical: 4.h),
              child: InkWell(
                onTap: () {
                  setState(() {
                    _selectedYear = year;
                  });
                },
                borderRadius: BorderRadius.circular(12.r),
                child: AnimatedContainer(
                  duration: const Duration(milliseconds: 200),
                  padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
                  decoration: BoxDecoration(
                    color: isSelected 
                        ? ExpenseTheme.primaryBlue.withValues(alpha: 0.1)
                        : Colors.transparent,
                    borderRadius: BorderRadius.circular(12.r),
                    border: Border.all(
                      color: isSelected 
                          ? ExpenseTheme.primaryBlue 
                          : Colors.transparent,
                      width: 2,
                    ),
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        child: Text(
                          year.toString(),
                          style: TextStyle(
                            fontSize: 18.sp,
                            fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
                            color: isSelected 
                                ? ExpenseTheme.primaryBlue 
                                : ExpenseTheme.textPrimary,
                          ),
                        ),
                      ),
                      if (isCurrentYear)
                        Container(
                          padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                          decoration: BoxDecoration(
                            color: ExpenseTheme.incomeGreen,
                            borderRadius: BorderRadius.circular(12.r),
                          ),
                          child: Text(
                            '今年',
                            style: TextStyle(
                              fontSize: 10.sp,
                              fontWeight: FontWeight.w500,
                              color: Colors.white,
                            ),
                          ),
                        ),
                      if (isSelected)
                        Icon(
                          Icons.check_circle,
                          color: ExpenseTheme.primaryBlue,
                          size: 20.sp,
                        ),
                    ],
                  ),
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  /// 构建操作按钮
  Widget _buildActions() {
    return Container(
      padding: EdgeInsets.all(16.w),
      child: Row(
        children: [
          Expanded(
            child: TextButton(
              onPressed: () => Navigator.of(context).pop(),
              style: TextButton.styleFrom(
                padding: EdgeInsets.symmetric(vertical: 12.h),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8.r),
                ),
              ),
              child: Text(
                '取消',
                style: TextStyle(
                  fontSize: 16.sp,
                  color: ExpenseTheme.textSecondary,
                ),
              ),
            ),
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: ElevatedButton(
              onPressed: _confirmSelection,
              style: ElevatedButton.styleFrom(
                backgroundColor: ExpenseTheme.primaryBlue,
                foregroundColor: Colors.white,
                padding: EdgeInsets.symmetric(vertical: 12.h),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8.r),
                ),
              ),
              child: Text(
                '确定',
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 滚动到选中的年份
  void _scrollToSelectedYear() {
    final index = _years.indexOf(_selectedYear);
    if (index != -1 && _scrollController.hasClients) {
      final itemHeight = 56.h; // 估算的项目高度
      final offset = index * itemHeight;
      _scrollController.animateTo(
        offset,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  /// 确认选择
  void _confirmSelection() {
    widget.onYearSelected(_selectedYear);
    Navigator.of(context).pop();
  }
}

/// 显示增强的年份选择器
Future<int?> showEnhancedYearPicker({
  required BuildContext context,
  required int initialYear,
  int? startYear,
  int? endYear,
  String? title,
}) async {
  int? selectedYear;
  
  await showDialog<int>(
    context: context,
    barrierDismissible: true,
    builder: (context) => EnhancedYearPicker(
      initialYear: initialYear,
      startYear: startYear,
      endYear: endYear,
      title: title,
      onYearSelected: (year) {
        selectedYear = year;
      },
    ),
  );
  
  return selectedYear;
}

/// 年份选择器按钮组件
class YearPickerButton extends StatelessWidget {
  final int selectedYear;
  final Function(int) onYearChanged;
  final int? startYear;
  final int? endYear;
  final String? title;

  const YearPickerButton({
    super.key,
    required this.selectedYear,
    required this.onYearChanged,
    this.startYear,
    this.endYear,
    this.title,
  });

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () async {
        final year = await showEnhancedYearPicker(
          context: context,
          initialYear: selectedYear,
          startYear: startYear,
          endYear: endYear,
          title: title,
        );
        
        if (year != null) {
          onYearChanged(year);
        }
      },
      borderRadius: BorderRadius.circular(12.r),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
        decoration: BoxDecoration(
          color: ExpenseTheme.softBlue,
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(color: ExpenseTheme.lightBlue),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.youtube_searched_for,
              color: ExpenseTheme.primaryBlue,
              size: 20.sp,
            ),
            SizedBox(width: 8.w),
            Text(
              '$selectedYear年',
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w500,
                color: ExpenseTheme.textPrimary,
              ),
            ),
            SizedBox(width: 4.w),
            Icon(
              Icons.arrow_drop_down,
              color: ExpenseTheme.textSecondary,
              size: 20.sp,
            ),
          ],
        ),
      ),
    );
  }
}
